# Clean up
rm(list = ls())
Sys.setenv(LANG = "en")

# Set working directory: please set your own
#setwd("~/Dropbox/sanctions_replication/")

# Load necessary packages
library(tidyverse)
library(readstata13)

# Import dataset
data <- read.dta13("data/survey_clean.dta")

# Make the plot
figureb4 <- data %>%
  drop_na(pbeliefs_vox_num, 
          pmoral_vox_num,
          pharm_vox_num,
          normexpect_vox_num,
          smoral_vox_num,
          sharm_vox_num,
  ) %>%
  select("pbeliefs_vox_num", "pmoral_vox_num", "pharm_vox_num",
         "normexpect_vox_num", "smoral_vox_num", "sharm_vox_num")  %>%
  mutate(socially_self = ifelse(pbeliefs_vox_num < 4, "No", "Yes")) %>%
  mutate(morally_self = ifelse(pmoral_vox_num < 4, "No", "Yes")) %>%
  mutate(harmful_self = ifelse(pharm_vox_num < 3, "Yes", "No")) %>%
  mutate(socially_others = ifelse(normexpect_vox_num < 4, "No", "Yes")) %>%
  mutate(morally_others = ifelse(smoral_vox_num < 4, "No", "Yes")) %>%
  mutate(harmful_others = ifelse(sharm_vox_num < 3, "Yes", "No")) %>%
  
  select("socially_self", "morally_self", "harmful_self",
         "socially_others", "morally_others", "harmful_others")  %>%
  
  `colnames<-`(c("Socially Appropriate (Self)", "Morally Appropriate (Self)", "Harmful (Self)", 
                 "Socially Appropriate (Others)", "Morally Appropriate (Others)", "Harmful (Others)")) %>%
  # make into long format
  pivot_longer(cols = c(`Socially Appropriate (Self)`:`Harmful (Others)`),
               names_to = "Group") %>%
  
  mutate(Variable = ifelse(Group %in% c("Socially Appropriate (Self)", "Socially Appropriate (Others)"), "Socially Appropriate",
                           ifelse(Group %in% c("Morally Appropriate (Self)", "Morally Appropriate (Others)"), "Morally Appropriate", 
                                  "Harmful"))) %>%  
  
  mutate(Order = ifelse(Group %in% c("Socially Appropriate (Self)", "Morally Appropriate (Self)", "Harmful (Self)"), "First-order (self)",
                        "Second-order (others)"))  %>%
  
  group_by(Variable) %>%
  mutate(overall_n = n()) %>%
  ungroup() %>%
  group_by(Group, value) %>%
  mutate(group_n = n(), na.rm = T) %>%
  mutate(prop = group_n / overall_n, na.rm = T) %>%
  mutate(percent = prop * 100, na.rm = T)  %>%
  ggplot(aes(x = value, y = percent, group = Order, color = Order, na.rm = TRUE)) + 
  geom_bar(aes(y = ..prop.., linetype = value), position = position_dodge(width = 1), fill = "white", na.rm = TRUE) +
  geom_text(aes(y = ..prop.., label = scales::percent(..prop..)),
            stat = 'count', position = position_dodge(width = 1), vjust = -0.5) +
  theme_bw() +
  labs(x = "Survey response", y = "Share of respondents") +
  scale_color_manual(values = c("red", "blue")) +
  scale_fill_manual(values = c("red", "blue")) +
  facet_wrap(~Variable)
figureb4

ggsave("figures/figureb4.png", plot = figureb4, width = 25, height = 12.5, units = "cm")